#!/bin/dash

# do touch
compilers="gcc tcc"
components="./components/"

# dont touch
COMPILER=""
MODE_INSTALL=false
MODE_BUILD=false
MODE_CLEAN_PRE=false
MODE_CLEAN_POST=false
TARGET=""
LIBS=""
libs=""

select_compiler() {
	for i in $1; do
		if [ ! -z "$(command -v "$i")" ]; then
			printf 'Using: %s\n' "$i"
			COMPILER="$i"
			break
		fi
	done
}

calc() {
	awk "BEGIN{print $*}"
}

build_components() {
	file_count=$(ls -1 "$2" | sed -n '/^.*.[c]$/p' | wc -l)
	step_size="$(calc "1/$file_count*100" | cut -f1 -d'.')"
	if [ ! -z "$1" ]; then
		step=$step_size
		for x in $(ls -1 "$2" | sed -n '/^.*.[c]$/p'); do
			printf '[%3s%%]: %20s\n' $step "$x"
			$1 $CFLAGS -c "$2/$x" -o "$2/$(echo $x | cut -f1 -d.).o"
			step=$(expr $step + $step_size)
		done
	else
		printf 'No Compiler set!\n'
		exit 1
	fi
}

build_main() {
	echo "Building Main!"
	$1 $CFLAGS -D"$TARGET" -c "main.c" -o main.o
}

build_finalize() {
	echo "Creating .out file.\n"
	$1 main.o $(ls -1 components/ | sed -n 's/.*/components\/&/; /^.*.[c]$/p') -L"$LIBS" -l"$libs"
}

# main script.
while getopts "qs:cChvibT:" opt; do
	case "$opt" in
		h)
			printf '%s\n' "gr4 compile script."
			exit 0
			;;
		v)
			printf '%s\n' "0.0.1"
			exit 0
			;;
		i)
			MODE_INSTALL=true
			;;
		b)
			MODE_BUILD=true
			;;
		s)
			case "$OPTARG" in
				push)
					if [ ! -d "staging" ]; then
						mkdir ./staging
						touch ./staging/.stage
					fi

					# make a tar.
					tar jcvf "./staging/$(date +%Y-%m-%d-%H-%M-%S).tar.bz2" --exclude "make.sh" --exclude "staging" ./
					;;
				pop)

					if [ ! -d "staging" ]; then
						echo "[no staging folder]"
						return
					fi
					;;
				*)
					echo "[unknown stage operation]"
					;;
			esac
			;;
			
		c)
			MODE_CLEAN_PRE=true
			;;
		C)
			MODE_CLEAN_POST=true
			;;
		T)
			TARGET="$OPTARG"
			# TODO: Fix this.
			LIBS="/usr/X11R6/lib"
			libs="X11"
			;;
		q)
			# Secret.
			MODE_CLEAN_PRE=true
			MODE_BUILD=true
			TARGET="LINUX_X11"
			# TODO: Fix this.
			LIBS="/usr/X11R6/lib"
			libs="X11"
			;;
		\?)
			printf '%s\n' "what?"
			;;
	esac
done
shift $(expr $OPTIND - 1)

if $MODE_CLEAN_PRE; then
	echo "prebuild clean..."
	rm -f *.o components/*.o
fi

if $MODE_BUILD; then
	printf '%s\n' "Building Components..."
	select_compiler "$compilers"
	build_components "$COMPILER" "$components"
	printf '%s' "done."
	build_main "$COMPILER"
	build_finalize "$COMPILER"
fi

if $MODE_CLEAN_POST; then
	echo "postbuild clean..."
	rm -f *.o components/*.o
fi

if $MODE_INSTALL; then
	echo "hello!"
fi

